import { onMounted } from 'vue'
import { useAppStore } from '@/store/app'

import { DictHooksOptions, ReturnDTO } from './data.d'

export const useDict = <T extends string = string>(options: DictHooksOptions<T>) => {
  const defaultOptions: DictHooksOptions<T> = {
    createdIsNeed: true,
    dictTypeList: [],
    dictMap: {} as Record<T, ReturnDTO[]>,
  }

  const mergeDefaultOptions = (options: DictHooksOptions<T>, props: DictHooksOptions<T>): DictHooksOptions<T> => {
    let key: keyof DictHooksOptions<T>
    for (key in options) {
      if (!Object.getOwnPropertyDescriptor(props, key)) {
        props[key] = options[key] as any
      }
    }
    return props
  }
  // 覆盖默认值
  const state = mergeDefaultOptions(defaultOptions, options)

  onMounted(() => {
    if (state.createdIsNeed) {
      getDictList()
    }
  })

  const getDictList = () => {
    if (!state.dictTypeList.length) return

    const appStore = useAppStore()
    const filter = appStore.dictList.filter((dict) => state.dictTypeList.includes(dict.dictType as T))
    filter.forEach((item, i) => {
      state.dictMap![item.dictType as T] = item.dictList
    })
  }

  return {
    getDictList,
  }
}
